package com.jinxin.platform.cdfaceacs.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdfaceacs.bean.CdfaceacsAuthTempalte;
import com.jinxin.platform.cdfaceacs.bean.CdfaceacsDevice;
import com.jinxin.platform.cdfaceacs.bean.CdfaceacsWorkDevice;
import com.jinxin.platform.cdfaceacs.bean.CdfaceacsWorker;
import com.jinxin.platform.cdfaceacs.common.Constant;
import com.jinxin.platform.cdfaceacs.common.SysUserVO;
import com.jinxin.platform.cdfaceacs.mapper.*;
import com.jinxin.platform.cdfaceacs.rpc.SysUserRpc;
import com.jinxin.platform.cdfaceacs.service.IFaceAcsWorkerService;
import com.jinxin.platform.cdfaceacs.utils.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-05-20
 * @Author: Lingnan
 **/
@Slf4j
@Service
public class FaceAcsWorkerServiceImpl implements IFaceAcsWorkerService {
    @Autowired
    private CdfaceacsWorkerMapper workerMapper;
    @Autowired
    private CdfaceacsWorkDeviceMapper workDeviceMapper;
    @Autowired
    private CdfaceacsDeviceMapper deviceMapper;
    @Autowired
    private CdfaceacsAuthTempalteMapper authTempalteMapper;
    @Autowired
    private CdfaceacsOpenRecordMapper openRecordMapper;
    @Resource
    private IdWorker idWorker;
    @Autowired
    private SysUserRpc sysUserRpc;

    @Override
    public List<CdfaceacsWorker> listPage(HashMap param) {
        return workerMapper.listPage(param);
    }

    @Override
    public int listPageCount(HashMap param) {
        return workerMapper.listPageCount(param);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult delete(String id) {
        if(StringUtils.isEmpty(id)){
            return JsonResult.error("Id不存在");
        }
        int result = workerMapper.deleteByKey(id);
        if(result > 0){
            workDeviceMapper.deleteByWorkerId(id);
            return JsonResult.ok("删除成功","");
        }
        return JsonResult.error("删除失败");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult deleteAll(String params) {
        if(StringUtils.isEmpty(params)){
            return JsonResult.error("参数不存在");
        }
        JSONObject jsonObject = JSONObject.parseObject(params);
        if(jsonObject.containsKey("rIds")){
            String idArr = jsonObject.getString("rIds");
            List<String> idList = JSONArray.parseArray(idArr, String.class);
            if(idList.size() > 0){
                int num = workerMapper.deleteByIds(idList);
                if (num > 0){
                    // 删除工人-设备对应表数据
                    idList.forEach(workId->{
                        workDeviceMapper.deleteByWorkerId(workId);
                    });
                    return JsonResult.ok("删除成功","");
                }else {
                    return JsonResult.error("删除失败");
                }
            }else {
                return JsonResult.error("删除失败");
            }
        }
        return JsonResult.error("参数错误，删除失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult batchAuth(String authTemplateId,String authTemplate,String idStr,String issueDevices) {
        if(StringUtils.isEmpty(authTemplateId) || StringUtils.isEmpty(authTemplate) || StringUtils.isEmpty(idStr)){
            return JsonResult.error("参数不存在");
        }
        if(StringUtils.isEmpty(issueDevices)){
            return JsonResult.error("下发设备未选择");
        }
        JSONObject jsonObject = JSONObject.parseObject(idStr);
        if(jsonObject.containsKey("rIds")){
            String idArr = jsonObject.getString("rIds");
            List<String> idList = JSONArray.parseArray(idArr, String.class);
            if(idList.size() > 0){
                // 时间段权限批量设置
                JSONArray deviceArr = JSONArray.parseArray(issueDevices);
                CdfaceacsAuthTempalte authTempalte = authTempalteMapper.selectByKey(authTemplateId);
                if(authTempalte == null){
                    return JsonResult.error("获取权限模板失败，操作失败");
                }
                List<String> timePeriodList = new ArrayList<>();
                String selection1Start = authTempalte.getSelection1Start();
                if(!StringUtils.isEmpty(selection1Start)){
                    timePeriodList.add(selection1Start);
                }
                String selection1End = authTempalte.getSelection1End();
                if(!StringUtils.isEmpty(selection1End)){
                    timePeriodList.add(selection1End);
                }
                String selection2Start = authTempalte.getSelection2Start();
                if(!StringUtils.isEmpty(selection2Start)){
                    timePeriodList.add(selection2Start);
                }
                String selection2End = authTempalte.getSelection2End();
                if(!StringUtils.isEmpty(selection2End)){
                    timePeriodList.add(selection2End);
                }
                String selection3Start = authTempalte.getSelection3Start();
                if(!StringUtils.isEmpty(selection3Start)){
                    timePeriodList.add(selection3Start);
                }
                String selection3End = authTempalte.getSelection3End();
                if(!StringUtils.isEmpty(selection3End)){
                    timePeriodList.add(selection3End);
                }
                String timePeriod = String.join(",",timePeriodList);
                if(deviceArr != null && deviceArr.size() > 0){
                    int count = workerMapper.batchAuthByIds(authTemplateId, authTemplate, idList);
                    if(count > 0){
                        idList.forEach(workId->{
                            for (int i = 0; i < deviceArr.size(); i++) {
                                JSONObject obj = deviceArr.getJSONObject(i);
                                CdfaceacsWorkDevice workDevice = new CdfaceacsWorkDevice();
                                String deviceId = obj.getString("id");
                                CdfaceacsDevice device = deviceMapper.selectByKey(deviceId);
                                if(device == null){
                                    log.info("获取设备信息失败");
                                    throw new RuntimeException("获取设备信息失败");
                                }
                                CdfaceacsWorker worker = workerMapper.selectByKey(workId);
                                if(worker == null){
                                    log.info("获取工人信息失败");
                                    throw new RuntimeException("获取人员信息失败");
                                }
                                String password = device.getPassword();
                                String serialNum = device.getSerialNum();
                                String productCode = device.getProductCode();
                                String userName = worker.getName();
                                String faceData = worker.getFaceData();
                                JsonResult jsonResult;
                                HashMap param = new HashMap();
                                param.put("workId",workId);
                                param.put("deviceId",deviceId);
                                CdfaceacsWorkDevice workDeviceInfo = workDeviceMapper.selectOne(param);
                                String personId;
                                if(workDeviceInfo == null){
                                    personId = String.valueOf(idWorker.nextId());
                                    jsonResult = sysUserRpc.personCreateOrUpdate(password, personId, serialNum, productCode, userName, false);
                                    if(jsonResult.getSuccess()){
                                        workDevice.setId(String.valueOf(idWorker.nextId()));
                                        workDevice.setWorkId(workId);
                                        workDevice.setDeviceId(deviceId);
                                        workDevice.setDeviceName(obj.getString("name"));
                                        workDevice.setPersonId(personId);
                                    }
                                }else {
                                    personId = workDeviceInfo.getPersonId();
                                    jsonResult = sysUserRpc.personCreateOrUpdate(password, personId, serialNum, productCode, userName, true);
                                }
                                if(jsonResult.getSuccess()){
                                    // 照片创建或更新
                                    if(!StringUtils.isEmpty(faceData)){
                                        faceData = faceData.replaceFirst(Constant.IMG_BASE64_PREFIX,"");
                                        if(workDeviceInfo != null && !StringUtils.isEmpty(workDeviceInfo.getFaceId())){
                                            String faceId = workDeviceInfo.getFaceId();
                                            JsonResult jsonResult2 = sysUserRpc.photoCreationOrUpdate(password, personId, faceId, faceData, serialNum, productCode, true);
                                            if(!jsonResult2.getSuccess()){
                                                log.info("照片更新失败");
                                                throw new RuntimeException("照片更新失败");
                                            }
                                        }else {
                                            String faceId = String.valueOf(idWorker.nextId());
                                            JsonResult jsonResult1 = sysUserRpc.photoCreationOrUpdate(password, personId, faceId, faceData, serialNum, productCode, false);
                                            if(jsonResult1.getSuccess()){
                                                workDevice.setFaceId(faceId);
                                            }else {
                                                log.info("照片创建失败");
                                                throw new RuntimeException("照片创建失败");
                                            }
                                        }
                                    }
                                    JsonResult jsonResult2 = sysUserRpc.timePeriodPermissionSetting(password, personId, timePeriod, serialNum, productCode);
                                    if(jsonResult2.getSuccess()){
                                        if(workDeviceInfo == null){
                                            workDeviceMapper.insert(workDevice);
                                        }
                                    }else {
                                        log.info("时间权限设置失败");
                                        throw new RuntimeException("时间权限设置失败");
                                    }
                                }else {
                                    log.info("人员新增或修改失败");
                                    throw new RuntimeException("人员创建失败");
                                }
                            }
                        });
                    }else {
                        throw new RuntimeException("批量授权失败");
                    }

                }
                return JsonResult.ok("批量授权成功");
            }else {
                return JsonResult.error("操作失败");
            }
        }
        log.info("参数错误，操作失败");
        return JsonResult.error("参数错误，操作失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult cancelBatchAuth(String idStr) {
        if(StringUtils.isEmpty(idStr)){
            return JsonResult.error("参数不存在");
        }
        JSONObject jsonObject = JSONObject.parseObject(idStr);
        if(jsonObject.containsKey("rIds")){
            String idArr = jsonObject.getString("rIds");
            List<String> idList = JSONArray.parseArray(idArr, String.class);
            if(idList.size() > 0){
//                List<String> idList = new ArrayList<>();
//                idPIdList.forEach(item->{
//                    idList.add(item.split(",")[0]);
//                });
                int num = workerMapper.cancalBatchAuthByIds(idList);
                if (num > 0){
                    // 删除工人-设备对应表数据
                    idList.forEach(workId->{
//                        String[] workPArr = workAndPerId.split(",");
//                        String workId = workPArr[0];
//                        String personId = workPArr.length > 1 ? workPArr[1] : "";
                        HashMap param = new HashMap();
                        param.put("workId",workId);
                        List<CdfaceacsWorkDevice> list = workDeviceMapper.list(param);
                        AtomicInteger count = new AtomicInteger();
                        list.forEach(workDevice->{
                            CdfaceacsDevice device = deviceMapper.selectByKey(workDevice.getDeviceId());
                            if(device== null){
                                throw new RuntimeException("获取设备信息失败");
                            }
                            String password = device.getPassword();
                            String serialNum = device.getSerialNum();
                            String personId = workDevice.getPersonId();
                            // 时间段权限删除指令返回应答超时是正常的，实际是删除成功了的
                            JsonResult jsonResult = sysUserRpc.timePeriodPermissionDeletion(password, personId, serialNum);
                            if(jsonResult.getSuccess()){
                                // 删除设备端人员和人脸
                                JsonResult jsonResult1 = sysUserRpc.deletePersonnelBatch(password, personId, serialNum);
                                if(jsonResult1.getSuccess()){
                                    String faceId = workDevice.getFaceId();
                                    if(!StringUtils.isEmpty(faceId)){
                                        sysUserRpc.photoDeletion(password,faceId,serialNum);
                                    }
                                    count.getAndIncrement();
                                }
                            }else {
                                throw new RuntimeException("时间权限设置失败");
                            }
                            // CDFACEACS_OPEN_RECORD 记录表中的OPEN_USER_ID字段置为null
                            if(!StringUtils.isEmpty(personId)){
                                openRecordMapper.setUserIdNullByUserId(personId);
                            }
                        });
                        if(count.get() > 0 && count.get() == list.size()){
                            workDeviceMapper.deleteByWorkerId(workId);
                        }
                    });
                    return JsonResult.ok("取消授权成功","");
                }else {
                    throw new RuntimeException("取消授权失败");
                }
            }else {
                throw new RuntimeException("取消授权失败");
            }
        }
        return JsonResult.error("参数错误，取消授权失败");
    }

    @Override
    public JsonResult saveOrUpdate(CdfaceacsWorker record) {
        if (record == null){
            return JsonResult.error("参数错误，操作失败");
        }
        String id = record.getId();
        int count;
        String msg = "";
        if(StringUtils.isEmpty(id)){
            SysUserVO currentUser = sysUserRpc.getCurrentUser();
            if(currentUser == null){
                return JsonResult.error("获取当前用户信息失败");
            }
            record.setCreateUserId(currentUser.getUserId());
            record.setCreateUserName(currentUser.getUserAccount());
            record.setCreateTime(LocalDateTime.now());
            record.setId(String.valueOf(idWorker.nextId()));
            count = workerMapper.insert(record);
            msg = "新增成功";
        }else {
            count = workerMapper.updateByKey(record);
            msg = "更新成功";
        }
        if(count > 0){
            return JsonResult.ok(msg,"");
        }else {
            return JsonResult.error("操作失败，请重试");
        }
    }

    @Override
    public CdfaceacsWorker selectById(String id) {
        if(StringUtils.isEmpty(id)){
            return null;
        }
        return workerMapper.selectByKey(id);
    }

    @Override
    public CdfaceacsWorker selectOne(HashMap param) {
        return workerMapper.selectOne(param);
    }
}
